package com.shujia.stream

import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}

object Demo3Window {
  def main(args: Array[String]): Unit = {
    //1、创建Spark执行环境
    val conf = new SparkConf()
    conf.setAppName("wc")
    conf.setMaster("local[2]")

    val sc = new SparkContext(conf)

    /**
     * Durations.seconds(5): 指定处理批次的大小
     */
    //2、创建Spark Streaming执行环境
    val ssc = new StreamingContext(sc, Durations.seconds(5))

    /**
     * nc -lk 8888
     * nc用于模拟实时数据源的工具
     * yum install nc
     */
    //3、读取数据
    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    //统计单词的数量
    val kvDS: DStream[(String, Int)] = linesDS
      .flatMap(line => line.split(","))
      .map(word => (word, 1))

    /**
     * 每隔5秒统计最近15秒单词的数量
     */
    val countDS: DStream[(String, Int)] = kvDS
      .reduceByKeyAndWindow(
        (x: Int, y: Int) => x + y,
        Durations.seconds(15), //窗口大小
        Durations.seconds(5) //滑动时间
      )

    countDS.print()


    //4、启动spark streaming程序
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()
  }
}
